/**
 * Copyright (C) 2016 Robinhood Markets, Inc.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.jinatonic.confetti.confetto;

import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.utils.Color;
import ohos.agp.utils.Matrix;
import ohos.agp.utils.RectFloat;
import ohos.media.image.PixelMap;

import java.lang.ref.WeakReference;

public class BitmapConfetto extends Confetto {
    private final PixelMap bitmap;
    private final float bitmapCenterX;
    private final float bitmapCenterY;

    private WeakReference<PixelMapHolder> pixelMapHolder;

    public BitmapConfetto(PixelMap bitmap) {
        this.bitmap = bitmap;
        this.bitmapCenterX = bitmap.getImageInfo().size.width / 2f;
        this.bitmapCenterY = bitmap.getImageInfo().size.height / 2f;
        pixelMapHolder = new WeakReference<>(new PixelMapHolder(bitmap));
    }

    @Override
    public int getWidth() {
        return bitmap.getImageInfo().size.width;
    }

    @Override
    public int getHeight() {
        return bitmap.getImageInfo().size.height;
    }

    @Override
    protected void drawInternal(
            Canvas canvas, Matrix matrix, Paint paint, float x, float y, float rotation, float percentageAnimated) {

        if (pixelMapHolder != null && pixelMapHolder.get() != null) {
            matrix.preTranslate(x, y);
            matrix.preRotate(rotation, bitmapCenterX, bitmapCenterY);

            canvas.setMatrix(matrix);

            canvas.drawPixelMapHolder(pixelMapHolder.get(), 0, 0, paint);
        }
    }

    @Override
    public boolean isOverdue() {
        return pixelMapHolder == null || pixelMapHolder.get() == null;
    }
}
